import React, { useState, useEffect, useRef } from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faSearch, faTimes } from '@fortawesome/free-solid-svg-icons'
import PropTypes from 'prop-types'
import './FileSearch.css'
import useKeyPress from '../hooks/useKeyPress'
const { ipcRenderer } = window.require('electron');


const FileSearch = (props) => {

  const { title, onFileSearch } = props

  const [value, setvalue] = useState('');
  const [inputActive, setInputActive] = useState(false);
  const node = useRef();

  const enterKeyPressed = useKeyPress(13)
  const escKeyPressed = useKeyPress(27)

  useEffect(() => {
    const handleSearchFile = () => {
      if(!inputActive) {
        setInputActive(true)
      }
    }
    ipcRenderer.on('search-file', handleSearchFile)
    return () => {
      ipcRenderer.removeListener('search-file', handleSearchFile);
    }
  }, [])

  //关闭搜索
  const closeSearch = () => {
    // e.preventDefault();
    setInputActive(false);
    setvalue('');
    onFileSearch('')
  }


  //当useEffect没有第二个参数时，会不停的调用
  useEffect(() => {
    if (enterKeyPressed && inputActive) {
      onFileSearch(value);
    }
    if (escKeyPressed && inputActive) {
      closeSearch();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  })

  useEffect(() => {
    if (inputActive) {
      node.current.focus();
    }
  }, [inputActive])

  return (
    <div className='alert alert-primary mb-0'>
      {
        !inputActive && <div className='d-flex justify-content-between align-items-center'>
          <span className='form-control fileSearchTitle'>
            {title}
          </span>
          <FontAwesomeIcon onClick={() => { setInputActive(true) }} title='搜索' size='lg' icon={faSearch}></FontAwesomeIcon>
        </div>
      }
      {
        inputActive && <div className='d-flex justify-content-between align-items-center'>
          <input ref={node} type="text" className="form-control input" onFocus={() => { setInputActive(true)}} value={value} onChange={(e) => { setvalue(e.target.value) }} placeholder="请输入搜索内容" />
          <FontAwesomeIcon onClick={closeSearch} size='lg' icon={faTimes}></FontAwesomeIcon>
        </div>
      }
    </div>
  )
}

FileSearch.prototype = {
  title: PropTypes.string,
  onFileSearch: PropTypes.func.isRequired
}

FileSearch.defaultProps = {
  title: '我的云文档',

}

export default FileSearch